package dao

import (
	"fmt"
	"github.com/go-redis/redis/v8"
	"golang.org/x/net/context"
	"log"
)

type RedisConf struct {
	URL  string `yaml:"url"`
	Port string `yaml:"port"`
}

var RedisClient *redis.Client
var Ctx = context.Background()

func InitRedis() (*redis.Client, error) {
	var c Conf
	var conf = c.getConf()

	RedisClient = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%s", conf.Redis.URL, conf.Redis.Port),
		Password: "",
		DB:       0,
	})

	// ping redis
	ctx := context.Background()
	_, err := RedisClient.Ping(ctx).Result()
	if err != nil {
		return nil, fmt.Errorf("failed to connect to Redis: %v", err)
	}

	fmt.Println("Redis connection successful!")
	return RedisClient, nil
}

func CloseRedis() {
	err := RedisClient.Close()
	if err != nil {
		log.Panicf("关闭Redis失败: %v", err)
	}
	fmt.Println("成功关闭Redis。")
}
